<?php

namespace catchAdmin\permissions\model;

use catchAdmin\permissions\model\UserHasGroup;
use catchAdmin\permissions\model\RoleHasGroup;
use catchAdmin\wechatopen\model\WechatopenMiniappUsers;
use catcher\base\CatchModel as Model;
use think\db\exception\DbException;
use catchAdmin\permissions\model\search\UsersGroupSearch;
use think\facade\Log;
use think\helper\Str;
use think\facade\Db;

/**
 *
 * @property int $id
 * @property string $group_name
 * @property int $parent_id
 * @property string $code
 * @property string $intro
 * @property int $created_at
 * @property int $updated_at
 * @property int $deleted_at
 * @property int $creator_id
 */
class UsersGroup extends Model
{
    use UsersGroupSearch;

    public $field = [
        //
        'id',
        // 用户组名称
        'group_name',
        // 父级ID
        'parent_id',
        // 用户组唯一标识，用英文表示
        'code',
        // 用户组介绍
        'intro',
        // 创建时间
        'created_at',
        // 更新时间
        'updated_at',
        // 软删除字段
        'deleted_at',
        // 创建人ID
        'creator_id',
    ];
    
    public $name = 'users_group';

    /**
     * 与用户表远程一对多关联，
     */
    public function groupable()
    {
        $morphModel = input('morphModel');
        if(isset($morphModel)){
            return $this->hasManyThrough($morphModel, UserHasGroup::class, 'group_id','id','id','groupable_id')->where('groupable_type',$morphModel);
        }else{
            $groupable_type = Db::table('user_has_group')->distinct(true)->field('groupable_type')->where('group_id','=',input('id',$this->id))->select(); //如没有输入用户组id则默认当前实例id
            $res = [];
            foreach ($groupable_type as $key => $morph){
                $res[$key] = $this->hasManyThrough($morph['groupable_type'], UserHasGroup::class, 'group_id','id','id','groupable_id')->where('groupable_type',$morph['groupable_type'])->hidden(['session_key','password']);  //无需输出的字段可以加入隐藏
            }
            return $res;
        }
    }

    /**
     * 与角色表远程一对多关联，
     */
    public function rolegroupable()
    {
        $morphModel = input('morphModel');
        if(isset($morphModel)){
            return $this->hasManyThrough($morphModel, RoleHasGroup::class, 'group_id','id','id','groupable_id')->where('groupable_type',$morphModel);
        }else{
            $groupable_type = Db::table('role_has_group')->distinct(true)->field('groupable_type')->where('group_id','=',input('id',$this->id))->select();
            $res = [];
            foreach ($groupable_type as $key => $morph){
                $res[$key] = $this->hasManyThrough($morph['groupable_type'], RoleHasGroup::class, 'group_id','id','id','groupable_id')->where('groupable_type',$morph['groupable_type']);  //无需输出的字段可以加入隐藏
            }
            return $res;
        }
    }

    /**
     * 列表数据
     *
     * @time 2020年01月09日
     * @return array
     * @throws DbException
     */
    public function getList(): array
    {
        return $this->catchSearch()
            ->catchOrder()
            ->select()->toTree();
    }

    /**
     * 获取子用户组IDS
     *
     * @time 2020年11月04日
     * @param $id
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @return mixed
     */
    public static function getChildrenGroupIds($id)
    {
        $groupIds = UsersGroup::field(['id', 'parent_id'])->select()->getAllChildrenIds([$id]);

        $groupIds[] = $id;

        return $groupIds;
    }

    /**
     * 以小程序用户唯一标识openid 初始化一个用户组。
     *
     * @time 2022年02月22日
     * @return mixed
     * @throws DbException
     */
    public function initMiniappUserGroup($token)
    {
        $user = WechatopenMiniappUsers::where('token',$token)->find();
        if($user){
            $userGroup = $this->where('code','=',$user->openid)->find();
            if($userGroup){
                return $userGroup;
            }else{
                $parentGroup = $this->where('code','=','wechatopen_miniapp_users')->find();
                $data['group_name'] = $user->openid.'好友组';
                $data['parent_id'] = $parentGroup->id;
                $data['code'] = $user->openid;
                $data['intro'] =  $user->openid.'好友组';
                $userGroup = $this->create($data);
                return $userGroup;
            }
        }else{
            return [];
        }
    }

}